import { readText } from '@tauri-apps/api/clipboard';
import { useControllableValue, useMemoizedFn } from 'ahooks';

export default function pasteable(Input: any) {
  return function (props: any) {
    const [value, onChange] = useControllableValue(props);
    const pasteCmd = useMemoizedFn(async (e: any) => {
      // ctrl+V|command+V
      const { metaKey, ctrlKey, keyCode, target } = e;
      const { tagName } = target;
      if (!['INPUT', 'TEXTAREA'].includes(tagName)) return;
      if (keyCode !== 86) return;
      if (!(metaKey || ctrlKey)) return;
      const text = (await readText()) || '';
      const start = target.selectionStart;
      const end = target.selectionEnd;
      const oValue = value || '';
      const str = oValue.substring(0, start) + text + oValue.substring(end);
      onChange(str);
      Promise.resolve().then(() => {
        target.selectionStart = target.selectionEnd = start + text.length;
      });
    });
    return (
      <Input
        {...props}
        value={value}
        onChange={(e: any) => onChange(e.target.value)}
        onKeyDownCapture={pasteCmd}
      />
    );
  };
}
